package com.whl.sm.controller.repair;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whl.sm.common.result.Result;
import com.whl.sm.common.util.UploadUtils;
import com.whl.sm.controller.BaseController;
import com.whl.sm.dto.SelectDto;
import com.whl.sm.dto.SelectIntDto;
import com.whl.sm.model.approval.VApproval;
import com.whl.sm.model.notice.Attachment;
import com.whl.sm.model.repair.RepairApply;
import com.whl.sm.model.system.OrgUserInfo;
import com.whl.sm.model.system.SysDict;
import com.whl.sm.service.notice.AttachmentService;
import com.whl.sm.service.repair.RepairApplyService;
import com.whl.sm.service.repair.RepairTaskService;
import com.whl.sm.service.system.OrgUserInfoService;
import com.whl.sm.service.system.OrgUserService;
import com.whl.sm.service.system.SysDictService;
import com.whl.sm.sysEnum.CommonEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuhaolun
 * @since 2021-11-28
 */
@RestController
@RequestMapping("/repair-apply")
@Slf4j
public class RepairApplyController extends BaseController {

    @Value("${ROOT_PATH}")
    private String rootPath;

    @Autowired
    private OrgUserService orgUserService;

    @Lazy
    @Autowired
    private RepairApplyService repairApplyService;

    @Autowired
    private OrgUserInfoService orgUserInfoService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private AttachmentService attachmentService;

    @RequestMapping("/list")
    public Result list(){
        QueryWrapper queryWrapper = getLikeParam("repair_description");
        setHttpRequestQueryWrapper(queryWrapper,"repair_type","step");
        queryWrapper.orderByDesc("update_time");
        queryWrapper.ne("is_del",1);
        Page listPage = repairApplyService.page(getPage(),queryWrapper);
        listPage.getRecords().stream().forEach(obj->{
            RepairApply repairApply = (RepairApply)obj;
            OrgUserInfo applicant = orgUserInfoService.getByUserId(repairApply.getApplicant());
            repairApply.setApplicantName(applicant==null?null:applicant.getUserName());
            OrgUserInfo operator = orgUserInfoService.getByUserId(repairApply.getOperator());
            repairApply.setOperatorName(operator==null?null:operator.getUserName());
            SysDict repairType = sysDictService.getById(repairApply.getRepairType());
            repairApply.setRepairTypeName(repairType==null?null:repairType.getDictValue());
            List<Attachment> applyImgLIst = attachmentService.getByDataId(repairApply.getId());
            if (applyImgLIst.size() > 0) {
                repairApply.setApplyImgList(applyImgLIst.stream().map(Attachment::getFile).collect(Collectors.toList()));
            }
        });
        return Result.ok(listPage);
    }

    @RequestMapping("/getByCurrent")
    public Result getByCurrent(@RequestParam("type") String type){
        String userId = orgUserService.getCurrentUserId();
        if (Objects.isNull(userId)){

            return  Result.fail();
        }
        QueryWrapper queryWrapper= new QueryWrapper();
        queryWrapper.eq("applicant",userId);
        queryWrapper.eq("applicant",userId);
        queryWrapper.orderByDesc("update_time");
        if (type.equals("notFin")){
            queryWrapper.isNull("complete_time");
        }else {
            queryWrapper.isNotNull("complete_time");
        }
        Page listPage = repairApplyService.page(getPage(),queryWrapper);
        return Result.ok(listPage);
    }

    @RequestMapping("/getDetail")
    public Result getWxApplyTaskDetail(String applyId){
        return repairApplyService.getDetailById(applyId);
    }

    @RequestMapping("/info/{id}")
    public Result applyInfo(@PathVariable("id") String id){
        RepairApply repairApply = repairApplyService.getById(id);
        return Result.ok(repairApply);
    }

    @RequestMapping("/applyDetail/{id}")
    public Result getApplyDetail(@PathVariable("id") String id){
        RepairApply repairApply = repairApplyService.getById(id);
        if(Objects.nonNull(repairApply.getRepairType())){
             SysDict linkType = sysDictService.getById(repairApply.getRepairType());
             repairApply.setRepairTypeName(linkType.getDictValue());
        }
        if (Objects.nonNull(repairApply.getApplicant())){
            OrgUserInfo applicant = orgUserInfoService.getByUserId(repairApply.getApplicant());
            repairApply.setApplicantName(applicant.getUserName());
        }
        List<Attachment> applyImgLIst = attachmentService.getByDataId(repairApply.getId());
        if (applyImgLIst.size() > 0) {
            repairApply.setApplyImgList(applyImgLIst.stream().map(Attachment::getFile).collect(Collectors.toList()));
        }
        return Result.ok(repairApply);
    }

    @RequestMapping("/update")
    public Result updateApply (@RequestBody RepairApply repairApply){
        return repairApplyService.update(repairApply);
    }

    @RequestMapping("/wxUpdate")
    public Result wxUpdateApply (RepairApply repairApply){
        if (repairApply.getStep() == 1){
            repairApply.setApplicant(orgUserService.getCurrentUserId());
        }
        return repairApplyService.update(repairApply);
    }


    @RequestMapping("/logDelete")
    public Result logicalDelete(@RequestBody List<String> idList){
        for (int i = 0; i <idList.size() ; i++) {
            repairApplyService.update(new UpdateWrapper<RepairApply>()
                    .eq("id",idList.get(i))
                    .set("is_del",1)
            );
        }
        return Result.ok();
    }

    @RequestMapping("/dispatch")
    public Result dispatch(@RequestParam("staffId")String staffId, @RequestParam("linkApplyId") String linkApplyId){
        return repairApplyService.dispatchTask(staffId,linkApplyId);
    }


    @RequestMapping("/applyStatus")
    public Result applyStatusDto(){
        List<SelectIntDto> resultList = new ArrayList<>();
        CommonEnum.RepairStatus[] statuses = CommonEnum.RepairStatus.values();
        for (CommonEnum.RepairStatus item : statuses ){
            SelectIntDto insertItem = new SelectIntDto(item.getStep(),item.getValue(),null,false);
            resultList.add(insertItem);
        }
        return Result.ok(resultList);
    }

    @RequestMapping("/uploadApImg")
    public Result uploadApproval(@RequestParam MultipartFile apImg , @RequestParam("dataId") String dataId,
                                 @RequestParam("dataType") String dataType,
                                 HttpServletRequest request){
        String path = "/repair/apImg";
        try{
            List<Map<String,Object>> fileList = UploadUtils.saveFile(request,path,this.rootPath,"apImg");
            String resultPath = "";
            if (fileList.size()>0){
                for (Map<String,Object> item :fileList){
                    Attachment attachment = new Attachment();
                    attachment.setDataId(dataId);
                    attachment.setDataType(dataType);
                    attachment.setFile(String.valueOf(item.get("filePath")));
                    attachment.setFileSize(Integer.valueOf(item.get("fileSize")+""));
                    attachment.setFileName(String.valueOf(item.get("originalName")));
                    attachment.setFileType(String.valueOf(item.get("mimeType")));
                    attachmentService.update(attachment);
                }
            }
        }catch (Exception e){
            log.error("维修申请图片上传失败----->"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }




}
